package com.mxf.example.security;

import com.mxf.example.entity.user.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class JwtUserDetailsService implements UserDetailsService {
    //模拟一下用户
    public static final List<SysUser> USERS = new ArrayList<>();
    static {
        SysUser user1 = new SysUser();
        user1.setUsername("admin");
        user1.setPassword(new BCryptPasswordEncoder().encode("123456"));
        SysUser user2 = new SysUser();
        user2.setUsername("test");
        user2.setPassword(new BCryptPasswordEncoder().encode("123"));
        USERS.add(user1);
        USERS.add(user2);
    }
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //继承了Security提供的UserDetailsService接口，实现loadUserByUsername这个方法，我们这里手动模拟从数据库搜出来一个叫USER的权限，
        List<GrantedAuthority> authorityList = new ArrayList<>();
        authorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
        authorityList.add(new SimpleGrantedAuthority("add"));
        //模拟用户
        SysUser userEntity =null;
        for (SysUser u: USERS) {
            if(u.getUsername().equals(username)){
                userEntity=u;
            }
        }
        if(null==userEntity){
            throw new UsernameNotFoundException(String.format("%s.这个用户不存在", username));
        }
        return new SysUser(userEntity.getUsername(),userEntity.getPassword(),authorityList);
    }

}
